package com.tinywind.admin.common.config.shiro.filter;

import com.tinywind.admin.common.base.BaseResult;
import com.tinywind.admin.common.utils.JsonTool;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author liuxingyu01
 * @date 2022-03-20 13:44
 * @description 重写authc过滤器，以适应前后端分离的需求
 **/
public class AuthcFilter extends FormAuthenticationFilter {
    final static Logger logger = LoggerFactory.getLogger(AuthcFilter.class);

    public AuthcFilter() {
        super();
    }

    /**
     * isAccessAllowed: 表示是否允许访问 ，如果允许访问返回true，否则false；
     * isAccessAllowed比onAccessDenied先执行
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().toUpperCase().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return true;
        }

        return super.isAccessAllowed(request, response, mappedValue);
    }

    /**
     * onAccessDenied：表示当访问拒绝时（认证失败了）是否已经处理了；如果返回 true 表示需要继续处理；
     * 如果返回 false 表示该拦截器实例已经处理了，将直接返回即可。
     * onAccessDenied 最后执行
     *
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        // 认证失败时的返回信息
        PrintWriter out = null;
        try {
            BaseResult baseResult = new BaseResult(BaseResult.CODE_NO_AUTHS, "认证失败, 无法访问系统资源", null);
            httpServletResponse.setContentType("application/json;charset=UTF-8");
            out = httpServletResponse.getWriter();
            out.write(JsonTool.toJsonString(baseResult));
        } catch (Exception e) {
            logger.error("AuthcFilter onAccessDenied 输出JSON异常。Exception = {e}", e);
        } finally {
            if (null != out) {
                out.close();
            }
        }
        return false;
    }

}
